package com.example.littleken.ormlitetext.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.example.littleken.ormlitetext.bean.School;
import com.example.littleken.ormlitetext.bean.Student;
import com.j256.ormlite.android.apptools.OrmLiteSqliteOpenHelper;
import com.j256.ormlite.support.ConnectionSource;
import com.j256.ormlite.table.TableUtils;

import java.sql.SQLException;

/**数据库帮助类，继承自OrmLiteSqliteOpenHelper
 * Created by littleken on 2018/5/9.
 */

public class DatabaseHelper extends OrmLiteSqliteOpenHelper {

    //构造方法设置为私有的，实现单例模式，只有一个对象能访问数据库
    private  DatabaseHelper(Context context){
        super(context,"text.db",null,2);
    }
    //那个唯一的对象
    private static DatabaseHelper sHelp = null;

    //synchronized同步的，保证多线程操作不会出错
    //外界只能通过这个方法获得那个数据库操作对象
    public static synchronized DatabaseHelper getLnstance(Context context){
        if(sHelp == null){
            sHelp = new DatabaseHelper(context);
        }
        return sHelp;
    }

    @Override
    public void onCreate(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource) {
        try {
            //超简单的建表操作，妈妈再也不用担心我要写一大堆建表sql语句了
            TableUtils.createTable(connectionSource, School.class);
            TableUtils.createTable(connectionSource, Student.class);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onUpgrade(SQLiteDatabase sqLiteDatabase, ConnectionSource connectionSource, int i, int i1) {
        try {
            //删表操作
            TableUtils.dropTable(connectionSource,Student.class,true);
            TableUtils.dropTable(connectionSource,School.class,true);
            //重新建表
            onCreate(sqLiteDatabase,connectionSource);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
